"use strict";
const BaseImpl = require("../basics/clz/baseimpl");
const Result = require("../basics/result");
const CardApi = require("../taobao/card");

/**
 * 通用服务
 */
class HomeImpl extends BaseImpl {
  /**
   * 查询小部件实例
   * @param {*} params 
   */
  async quereyWidgetList(params) {
    const { session } = params;
    const tempList = [{ name: "最新活动专区", template_id: "3000000063370972" }, { name: "耐克尊享福利", template_id: "3000000063369925" }, { name: "消息通知小部件", template_id: "3000000070514542" }, { name: "member-home", template_id: "3000000076082425" }, { name: "首页membercard", template_id: "3000000068537701" }];
    for (let i = 0; i < tempList.length; i++) {
      let el = tempList[i];
      const arrs = await CardApi.selectList(this.cloud, session, { template_id: el.template_id });
      if (!arrs) {
        continue;
      }
      let maxvo = null;
      for (let j = 0; j < arrs.length; j++) {
        const vo = arrs[j];
        if (vo.status == 'ONLINE') {
          el.entity_id = vo.app_id;
          el.status = vo.status;
          el.version = vo.version;
          el.template_version = vo.template_version;
          break;
        }
        if (!maxvo || maxvo.version < vo.version) {
          maxvo = vo;
        }
      }
      if (!el.entity_id) {
        el.entity_id = maxvo.app_id;
        el.status = maxvo.status;
        el.version = maxvo.version;
        el.template_version = maxvo.template_version;
      }
    }
    return tempList;
  }

  /**
   * 实例化小部件
   * @param {*} params 
   */
  async editWedgit(params) {
    const { session, entity_id, template_id, template_version, description } = params;
    if (entity_id) {
      await CardApi.updateapp(this.cloud, session, { entity_id, template_id, template_version });
    } else {
      if (!description) {
        throw Result.error(Result.constant.taobaofail, "描述必填");
      }
      await CardApi.instantiate(this.cloud, session, { description, template_id, template_version });
    }
    return true;
  }
}
module.exports = HomeImpl;